//
//  MovieShowViewController.m
//  MINFOBBS
//
//  Created by 蔡龙生 on 13-11-29.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "MovieShowViewController.h"
#import "SBJsonParser.h"
#import "DetectionSystemVersion.h"
#import "CinemaViewController.h"
#import "UIColor+expanded.h"
#import "MainSearchViewController.h"
@interface MovieShowViewController ()

@end

@implementation MovieShowViewController
@synthesize movieShowArray;
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (self.isSelf) {
        
    }
    else{
        [self BackButton];
        pageLimit=15;
        pageStart=0;
        loadMore=[[LoadMore alloc] init];
        loadMore.frame=CGRectMake(0, 0, 320, 32);
        [self.table addSubview:loadMore];
        self.table.showsVerticalScrollIndicator=YES;
        self.table.bounces=YES;
        [ self GetWeatherSearch:self.query Location:self.city];
    }
    self.table.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    	// Do any additional setup after loading the view.
}
- (void)viewWillDisappear:(BOOL)animated{
    [tRequest clearDelegatesAndCancel];
    [tRequest cancel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark - Get Lottery Ticket Data
-(void)GetWeatherSearch:(NSString*)Query Location:(NSString*)City{
    loadMore.loadingTitle.text=@"正在加载...";
    [loadMore.loadingAni startAnimating];
    tRequest=[[[ScreenAccess alloc]init]ASIGetSearch:Query  Start:pageStart Limit:pageLimit];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"movieshow"];
}

-(void)requestFinished:(ASIHTTPRequest*)request{
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    if ([request.username isEqual:@"movieshow"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            NSMutableArray *arrReturn=[[NSMutableArray alloc] init];
            [arrReturn addObject:[[Result objectForKey:@"Response"] objectForKey:@"Categories"]];
            for (int i=0; i<arrReturn.count; i++) {
                NSArray *arr=[[arrReturn objectAtIndex:i] objectForKey:@"Category"];
                for (int j=0; j<arr.count; j++) {
                    if([[[arr objectAtIndex:j] objectForKey:@"Entrance"] isEqual:@"MovieShow.SearchMovieShow"])
                    {
                      
                            if(movieShowArray==nil){
                                movieShowArray=[[NSMutableArray alloc] init];
                                total=[[[[arr objectAtIndex:j]objectForKey:@"Items"] objectForKey:@"total"] integerValue];
                            }
                            [movieShowArray addObjectsFromArray:[[[arr objectAtIndex:j] objectForKey:@"Items"] objectForKey:@"Item"]];
                        }
                }
            }
            [self.table reloadData];
            loadMore.frame=CGRectMake(0, self.table.contentSize.height-35, self.table.frame.size.width, 35);
            if (total==movieShowArray.count) {
                loadMore.loadingTitle.text=@"没有更多";
            }
            else{
                loadMore.loadingTitle.text=@"上拉加载更多";
            }
            [loadMore.loadingAni stopAnimating];
        }
        
    }
    loadingmore=NO;
}

-(void)requestFailed:(ASIHTTPRequest*)request{
    [loadMore.loadingAni stopAnimating];
    loadMore.loadingTitle.text=@"无网络";
    loadingmore=NO;
}

-(void)BackButton{
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if(self.isSelf){
//        return 2;
//    }
//    else{
        return movieShowArray.count;

//    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier=@"CellIdentifier";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell==nil){
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
//        cell.backgroundColor=[UIColor clearColor];
    }
    NSUInteger row=[indexPath row];
    NSString *dd=[[movieShowArray objectAtIndex:row] objectForKey:@"Title"];
    cell.textLabel.text=dd;
    cell.textLabel.font=[UIFont systemFontOfSize:14];
    
    cell.imageView.image=[UIImage imageNamed:@"电影演出"];
    cell.textLabel.backgroundColor=[UIColor clearColor];
    cell.textLabel.backgroundColor=[UIColor clearColor];
    if (indexPath.row%2==1) {
        UIView *vie=[[UIView alloc]init];
        vie.backgroundColor=[UIColor colorWithHexString:@"0xf3f3f3"];
        cell.backgroundView=vie;
    }
    else{
        cell.backgroundColor=[UIColor whiteColor];
    }

    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 38;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    if (self.isSelf) {
        UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.table.frame.size.width, 3)];
        img.image=[UIImage imageNamed:@"footLine"];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 3, self.table.frame.size.width, 35)];
         [btn addTarget:self action:@selector(PrseeMore) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:@"点击查看全部" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        [result addSubview:btn];
        [result addSubview:img];
        }
    return result;
}

#pragma mark - Table Delegate Methods
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 60;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSUInteger row=[indexPath row];
    NSString *lotteryName=[[movieShowArray objectAtIndex:row] objectForKey:@"href"];
    NSArray *tempStr=[lotteryName componentsSeparatedByString:@"="];
    NSString *queryStr=[tempStr objectAtIndex:1];
    CinemaViewController *cinemaViewController =[[CinemaViewController alloc] init];
    cinemaViewController.city=@"上海";
    cinemaViewController.query=queryStr;
    
    [self.navigationController pushViewController:cinemaViewController animated:YES];
}

- (MainSearchViewController *)menuContainerViewController {
    return (MainSearchViewController *)self.parentViewController;
}
-(void)PrseeMore{
    //    if (self.isSelf) {
    MovieShowViewController *jokecon=[[MovieShowViewController alloc]init];
    jokecon.query=self.query;
    [ [self menuContainerViewController].navigationController  pushViewController:jokecon animated:YES];
    //    }
    
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    PrevCGPoint=scrollView.contentOffset;
    if (movieShowArray.count<total) {
        if(PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height){
            if (loadingmore) return;
            loadingmore=YES;
            pageStart=pageStart+pageLimit;
//            NSLog(@"%d",pageStart);
            [self GetWeatherSearch:self.query Location:self.city];
        }
    }
   
}
@end
